package se.hrbustrc.hlgshopping.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import se.hrbustrc.hlgshopping.entity.OrderInfo;
import se.hrbustrc.hlgshopping.entity.OrderItem;
import se.hrbustrc.hlgshopping.service.OrderInfoService;
import se.hrbustrc.hlgshopping.mapper.OrderInfoMapper;
import org.springframework.stereotype.Service;
import se.hrbustrc.hlgshopping.service.OrderItemService;
import se.hrbustrc.hlgshopping.utils.Result;
import se.hrbustrc.hlgshopping.vo.OrderVO;
import se.hrbustrc.hlgshopping.vo.OrderRequestVO;
import se.hrbustrc.hlgshopping.entity.Address;
import se.hrbustrc.hlgshopping.service.AddressService;
import se.hrbustrc.hlgshopping.entity.Prosku;
import se.hrbustrc.hlgshopping.service.ProskuService;
import org.apache.ibatis.annotations.Param;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;

/**
 * @author qianbimo
 * @description 针对表【tb_order_info(订单信息表)】的数据库操作Service实现
 * @createDate 2025-09-12 18:47:05
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
        implements OrderInfoService{

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private ProskuService proskuService;

    public OrderInfoServiceImpl (OrderInfoMapper orderInfoMapper) {
        this.orderInfoMapper = orderInfoMapper;
    }

    /**
     * 添加订单（原有方法保持不变）
     * @param orderVO
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOrder(OrderVO orderVO) {
        try {
            // 1. 添加订单信息
            OrderInfo orderInfo = orderVO.getOrderInfo();
            if (orderInfo == null) {
                return new Result().error("订单信息不能为空");
            }

            orderInfo.setOrderno("ORD" + orderInfo.getUserid() + System.currentTimeMillis());
            this.save(orderInfo);

            // 2. 添加订单明细
            List<OrderItem> orderItemList = orderVO.getOrderItemList();
            if (orderItemList != null && !orderItemList.isEmpty()) {
                for (OrderItem orderItem : orderItemList) {
                    // 设置订单ID关联
                    orderItem.setOrderid(orderInfo.getId());
                    orderItemService.save(orderItem);
                }
            }

            return new Result().ok(orderInfo);
        } catch (Exception e) {
            return new Result().error("添加订单失败: " + e.getMessage());
        }
    }

    /**
     * 根据前端请求数据添加订单
     * @param orderRequestVO 前端传来的订单请求数据
     * @param userId 用户ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOrder(OrderRequestVO orderRequestVO, Long userId) {
        try {
            // 1. 校验参数
            if (orderRequestVO == null) {
                return new Result().error("订单信息不能为空");
            }

            if (orderRequestVO.getAddressId() == null) {
                return new Result().error("地址信息不能为空");
            }

            if (orderRequestVO.getGoods() == null || orderRequestVO.getGoods().isEmpty()) {
                return new Result().error("商品信息不能为空");
            }

            // 2. 获取地址信息
            Address address = addressService.getById(orderRequestVO.getAddressId());
            if (address == null) {
                return new Result().error("地址信息不存在");
            }

            // 3. 构建订单信息
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserid(userId);
            orderInfo.setOrderno("ORD" + userId + System.currentTimeMillis());
            orderInfo.setDeliverytimetype(orderRequestVO.getDeliveryTimeType());
            orderInfo.setPaytype(orderRequestVO.getPayType());
            orderInfo.setOrderstate(1); // 默认待付款状态
            orderInfo.setReceivercontact(address.getContactor());
            orderInfo.setReceivermobile(address.getPhone());
            orderInfo.setReceiveraddress(address.getAddress());
            orderInfo.setCreatetime(LocalDateTime.now());
            orderInfo.setUpdatetime(LocalDateTime.now());

            // 4. 计算订单金额
            BigDecimal totalMoney = BigDecimal.ZERO;
            Integer totalNum = 0;

            // 5. 构建订单明细列表
            List<OrderItem> orderItems = new ArrayList<>();

            for (OrderRequestVO.GoodsItem goodsItem : orderRequestVO.getGoods()) {
                // 获取SKU信息
                Prosku sku = proskuService.getById(goodsItem.getSkuId());
                if (sku == null) {
                    return new Result().error("商品SKU不存在，ID: " + goodsItem.getSkuId());
                }

                // 检查库存
                if (sku.getStocknum() < goodsItem.getCount()) {
                    return new Result().error("商品库存不足: " + sku.getSkuname());
                }

                // 计算金额
                BigDecimal skuPrice = new BigDecimal(sku.getPricesell());
                BigDecimal itemTotal = skuPrice.multiply(new BigDecimal(goodsItem.getCount()));
                totalMoney = totalMoney.add(itemTotal);
                totalNum += goodsItem.getCount();

                // 构建订单明细
                OrderItem orderItem = new OrderItem();
                orderItem.setSpuid(sku.getPid());
                orderItem.setName(sku.getSkuname());
                orderItem.setQuantity(goodsItem.getCount());
                orderItem.setRealpay(skuPrice);
                orderItem.setCurprice(skuPrice);
                orderItem.setAttrstext(sku.getSkuname());
                orderItem.setCreatetime(LocalDateTime.now());
                // TODO: 商品图片和属性文本需要从商品表中获取

                orderItems.add(orderItem);
            }

            // 运费暂时设置为0，可根据业务规则调整
            orderInfo.setPostfee(orderRequestVO.getPostFee());
            orderInfo.setTotalmoney(totalMoney);

            totalMoney = totalMoney.add(orderRequestVO.getPostFee());
            orderInfo.setPaymoney(totalMoney);
            // 设置订单总金额和总数量
            orderInfo.setTotalnum(totalNum);

            // 6. 保存订单信息
            this.save(orderInfo);

            // 7. 保存订单明细
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderid(orderInfo.getId());
                orderItemService.save(orderItem);
            }

            return new Result().ok(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error("添加订单失败: " + e.getMessage());
        }
    }

    /**
     * 删除订单（同时删除订单明细）
     * @param orderId
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOrder(int orderId) {
        try {
            // 先删除订单明细
            orderItemService.remove(
                    orderItemService.lambdaQuery()
                            .eq(OrderItem::getOrderid, orderId)
                            .getWrapper()
            );

            // 再删除订单信息
            this.removeById(orderId);

            return new Result().ok("订单删除成功");
        } catch (Exception e) {
            return new Result().error("删除订单失败: " + e.getMessage());
        }
    }

    /**
     * 修改订单状态
     * @param id
     * @param orderState
     * @return
     */

    @Override
    public Result upOrderState(Long id, Integer orderState) {
        try {
            System.out.println("尝试更新订单状态: ID=" + id + ", 状态=" + orderState);
            int result = orderInfoMapper.upOrderState(id,orderState);
            System.out.println("更新订单状态结果: " + result + " 行被更新");
            return new Result().ok("订单状态更新成功");
        } catch (Exception e) {
            System.out.println("更新订单状态失败: " + e.getMessage());
            e.printStackTrace();
            return new Result().error("更新订单状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单（包含订单明细）
     * @param orderId
     * @return
     */
    @Override
    public OrderInfo getOrder(Long orderId) {
        return this.getById(orderId);
    }

    /**
     * 根据订单编号获取订单
     * @param orderNo 订单编号
     * @return OrderInfo 订单信息
     */
    @Override
    public OrderInfo getOrderByNo(String orderNo) {
        return this.lambdaQuery()
                .eq(OrderInfo::getOrderno, orderNo)
                .one();
    }

    /**
     * 获取订单详情（包含订单信息和订单明细）
     * @param orderId 订单ID
     * @return OrderVO 订单详情
     */
    public OrderVO getOrderDetail(Long orderId) {
        OrderVO orderVO = new OrderVO();

        // 获取订单信息
        OrderInfo orderInfo = this.getById(orderId);
        orderVO.setOrderInfo(orderInfo);

        // 获取订单明细
        List<OrderItem> orderItemList = orderItemService.lambdaQuery()
                .eq(OrderItem::getOrderid, orderId)
                .list();
        orderVO.setOrderItemList(orderItemList);

        return orderVO;
    }
}




